package com.tiger.utils;

import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class Dva {

	/**
	 * 创建Dva线路
	 * @param cityName
	 * @param up
	 * @param down
	 * @param departTime 发车时间 可选
	 * @param returnTime 回程时间 可选
	 * @param type
	 * @param pool
	 * @param sid 可选
	 * @return
	 */
	public static boolean createLine(String cityName, Station up, Station down, LocalTime departTime, LocalTime returnTime, DvaType type, String pool, String sid) {
		Map<String, Object> params = new HashMap<>();
		params.put("city", cityName);
		params.put("up", up);
		params.put("down", down);
		
		if(pool != null) params.put("pool", pool);
		if(type != null) params.put("type", type);
		if(departTime != null) params.put("departTime", departTime);
		if(returnTime != null) params.put("returnTime", returnTime);
		
		String response = Http.postJson(Conf.get("dva.api") + "/lines" + (StringUtils.isEmpty(sid) ? "" : "?sid=" + sid), params);
		if (StringUtils.isBlank(response)) {
			return false;
		}
		if( !(response.startsWith("{") && response.endsWith("}") 
			|| response.startsWith("[") && response.endsWith("]")) ) {
			return false;
		}
		Object code = Json.fromJson(response, HashMap.class).get("code");
		return code != null && (Integer)code == 200;
	}
	
	public static class Coordinate {
		/**
		 * 经度
		 */
		private final double lng;

		/**
		 * 纬度
		 */
		private final double lat;
		
		public Coordinate() {
			this(0, 0);
		}
		public Coordinate(double lng, double lat) {
			this.lng = lng;
			this.lat = lat;
		}


		public double getLng() {
			return lng;
		}

		public double getLat() {
			return lat;
		}
	}
	
	public static class Station {
		
		private final String name;
		
		private final Coordinate pos;
		
		public Station() {
			this(null, null);
		}
		
		public Station(String name, Coordinate pos) {
			this.name = name;
			this.pos = pos;
		}
		
		public String getName() {
			return name;
		}
		public Coordinate getPos() {
			return pos;
		}
	}
	
	public static enum DvaType {
		CREATE,		// 发起
		FUNDING,	// 众筹
		JOIN,		// 众筹报名
		APPLY,		// 报名
		SEARCH		// 搜索
	}
	
	public static void main(String[] args) {
		boolean result = Dva.createLine(
				"深圳市", 
				new Station("上车点", new Coordinate(114.313534, 22.774776)), 
				new Station("下车点", new Coordinate(114.316924, 22.604802)), 
				LocalTime.now(),
				LocalTime.now().plusHours(12),
				DvaType.CREATE,
				"20161111",
				"111"
		);
		System.out.println(result);
	}
}
